package com.samehope.ar.component;

import com.samehope.ar.bo.CustomUserDetails;
import com.samehope.ar.bo.UserSessionBO;
import com.samehope.ar.entity.SysRole;
import com.samehope.ar.entity.SysUser;
import com.samehope.ar.service.ISysUserService;
import com.samehope.ar.util.IPUtils;
import com.samehope.ar.util.JwtTokenUtil;
import com.samehope.ar.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            LOGGER.info("checking username:{}", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                CustomUserDetails userDetails = (CustomUserDetails) this.userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {

                    SysUser user = userDetails.getUser();
                    // session 存储
                    UserSessionBO userSessionBO = new UserSessionBO();
                    userSessionBO.setCompanyId(user.getCompanyId());
                    userSessionBO.setMobile(user.getMobile());
                    userSessionBO.setIp(IPUtils.getIpAddress(request));

                    String projectId = request.getHeader("projectId");
                    if (StringUtils.isNotBlank(projectId)) {
                        userSessionBO.setProjectId(Long.valueOf(projectId));
                    }
                    userSessionBO.setName(user.getName());
                    userSessionBO.setUserId(user.getId());
                    SessionUtil.setUser(userSessionBO);

                    /**
                     * 查找权限, 根据用户ID, 企业ID, 项目ID查找权限
                     */
                    List<SysRole> roles = userService.getRoleListByUser(user.getId());
                    userDetails.setRoles(roles);

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    LOGGER.info("authenticated user:{}", username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
